using System.Linq.Expressions;

namespace K3Cloud.WebApi.Core.IoC.Extensions
{
    /// <summary>
    /// 表达式树节点计数器
    /// </summary>
    internal class NodeCounterVisitor : ExpressionVisitor
    {
        /// <summary>
        /// 节点总数
        /// </summary>
        public int Count { get; private set; }

        /// <summary>
        /// 重置计数器
        /// </summary>
        public void Reset()
        {
            Count = 0;
        }

        /// <summary>
        /// 访问表达式节点
        /// </summary>
        public override Expression? Visit(Expression? node)
        {
            if (node != null)
            {
                Count++;
            }
            return base.Visit(node);
        }

        /// <summary>
        /// 计算表达式树的节点数
        /// </summary>
        public static int CountNodes(Expression? expression)
        {
            if (expression == null)
                return 0;

            var counter = new NodeCounterVisitor();
            counter.Visit(expression);
            return counter.Count;
        }
    }
}
